from django.contrib.auth.models import AbstractUser
from django.db import models
from django.db.models.signals import post_save
from api.utils.db_functions import make_uuid
from api.utils.enums import RoleType


class User(AbstractUser):
    roles = models.CharField(
        help_text="用户角色",
        max_length=256,
        choices=RoleType.to_choices(),
        default=RoleType.OPERATE.value,
    )
    id = models.UUIDField(
        primary_key=True, help_text="ID of user", default=make_uuid, editable=True
    )
    username = models.CharField(default="", max_length=128, unique=True)
    mobile = models.CharField(max_length=11, unique=True, verbose_name="手机号")

    class Meta:
        db_table = "tb_users"
        verbose_name = "用户"
        verbose_name_plural = verbose_name

    def __str__(self):
        return self.username


class Profile(models.Model):
    user = models.OneToOneField(User, related_name="profile", on_delete=models.CASCADE)
    created_at = models.DateTimeField(auto_now_add=True)

    def __str__(self):
        return "%s's profile" % self.user

    class Meta:
        ordering = ("-created_at",)


def create_user_profile(sender, instance, created, **kwargs):
    if created:
        Profile.objects.create(user=instance)


class ShipAddress(models.Model):
    user = models.ForeignKey("User", on_delete=models.CASCADE, related_name="address")
    province = models.CharField("省", max_length=256)
    city = models.CharField("市", max_length=256)
    area = models.CharField("区", max_length=256)
    detailed = models.CharField("详细地址", max_length=256)
    default = models.BooleanField("是否默认地址", default=False)
    deleted = models.BooleanField("是否删除", default=False)


class Address(models.Model):

    number = models.IntegerField("省市区代码", default=0, null=True, blank=True)
    parent_number = models.IntegerField("父级代码", default=0, null=True, blank=True)
    pca = models.CharField("省市区", max_length=256, default="", null=True, blank=True)


post_save.connect(create_user_profile, sender=User)
